<template>
  <div>
    <!-- 产品上样推荐配置 -->
    <div v-show="!showEditPage">
      <search-form
        :search-config="searchConfig"
        :label-width="150"
        @clear="clearSearch"
        @search="handleSearch"
      />
    </div>
    <div v-show="!showEditPage">
      <table-box
        ref="ProSampleRecommend"
        :selected-arry.sync="tableSelected"
        :table-config="tableConfig"
        :other-filters="otherFilters"
        :other-raw="otherRaw"
        :off-set="-20"
        show-index
        show-selection
        @btnOperate="btnOperate"
        @selection-change="selectionChangeHandle"
      />
    </div>
    <div>
      <import-files v-if="importVisible" title="导入" :visible.sync="importVisible" :config="fileImportConfig" @success="handleImportSuccess" />
      <export-files v-if="exportVisible" title="导出" :config="exportConfig" :visible.sync="exportVisible" @success="handleExportSuccess" />
    </div>
    <div>
      <add-recommend-info v-if="showAddPage" ref="addRecommendInfo" :visible.sync="showAddPage" @success="handleEdit" />
      <add-pro-recommend v-if="showEditPage" ref="addProRecommend" :visible.sync="showEditPage" :detail-data="activatedData" @goBack="refreshTable" @success="refreshTable" />
    </div>
  </div>
</template>

<script>
import { delProRecommend } from '@/api/basicData'
import addProRecommend from './addProRecommend.vue'
import addRecommendInfo from './addRecommendInfo.vue'
import { queryCategoryData } from '@/api/proConfig'
import { getDictByPatchType } from '@/api/dataDict'

export default {
  name: 'ProSampleRecommend',
  components: { addProRecommend, addRecommendInfo },
  data() {
    return {
      exportVisible: false,
      importVisible: false,
      showAddPage: false,
      showEditPage: false,
      activatedData: {},
      divideOptions: [],
      searchConfig: [
        {
          label: '所属专区',
          prop: 'configStyleId',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `${process.env.VUE_APP_BASE_API}/api/v1/configStyle/page`,
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'styleName',
              value: 'id'
            },
            selectData: []
          },
          dialogConfig: {
            title: '所属专区',
            interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configStyle/page`,
            setting: [{ prop: 'styleCode', title: '编码' }, { prop: 'styleName', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '所属空间',
          prop: 'configSpaceId',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: `${process.env.VUE_APP_BASE_API}/api/v1/configSpace/page`,
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'spaceName',
              value: 'id'
            },
            selectData: []
          },
          dialogConfig: {
            title: '所属空间',
            interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configSpace/page`,
            setting: [{ prop: 'spaceCode', title: '编码' }, { prop: 'spaceName', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '产品定位',
          prop: 'proPosition',
          type: 'select',
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/SERIES_NAME?appCode=slm&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        },
        {
          label: '产品型号',
          prop: 'modelCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: '/select-service/api/v1/productModel/page',
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '产品型号',
            interfacePath: '/select-service/api/v1/productModel/page',
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' },
              {
                prop: 'saleSeriesCode',
                title: '系列编码'
              },
              {
                prop: 'saleSeriesName',
                title: '系列名称'
              }],
            pageFlag: true
          }
        },
        {
          label: '产品系列',
          prop: 'seriesCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: '/select-service/api/v1/productSaleSeries/page',
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
          },
          dialogConfig: {
            title: '产品系列',
            interfacePath: '/select-service/api/v1/productSaleSeries/page',
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '产品品类',
          prop: 'categoryCode',
          type: 'dialog',
          value: '',
          placeholder: '',
          config: {
            requestMethod: 'post',
            remoteUrl: '/select-service/api/v1/productCategory/page',
            paramField: 'keyWord', // 远程搜索参数名
            defaultProps: {
              label: 'name',
              value: 'code'
            },
            selectData: []
            // apiHeader: { 'permission-code': 'role_transfer_service', 'Permission-App': 'order-center' }
          },
          dialogConfig: {
            title: '产品品类',
            interfacePath: '/select-service/api/v1/productCategory/page',
            setting: [{ prop: 'code', title: '编码' }, { prop: 'name', title: '名称' }],
            pageFlag: true
          }
        },
        {
          label: '上样推荐方案',
          prop: 'recommendProgram',
          type: 'select',
          config: {
            remote: true,
            remoteUrl: `/data-dict/api/v2/dictionary/RECOMMEND_PROGRAM?appCode=slm&domainCode=marketing`,
            defaultProps: { label: 'dictName', value: 'dictCode' }
          }
        }
      ],
      tableSelected: [], // 初始化选择表格数据
      selectedRows: [], // 导出选择数据
      selectList: [], // 初始化选中
      otherFilters: [], // 表格额外查询条件
      otherRaw: {},
      tableConfig: {
        interfacePath: `${process.env.VUE_APP_BASE_API}/api/v1/configSampleRecommend/page`,
        hideSearchBar: true,
        // pageSize: 20,
        // sort: '',
        // order: 'desc',
        setting: [
          {
            prop: 'styleName',
            label: '所属专区',
            minWidth: 150,
            // show: false,
            className: 'btn-green',
            isButton: true,
            clickFun: this.handleDetail
          },
          {
            prop: 'spaceName',
            label: '所属空间',
            minWidth: 150
            // show: false,
            // className: 'btn-green',
            // isButton: true,
            // clickFun: this.handleDetail
          },
          {
            prop: 'recommendProgram',
            label: '产品推荐方案',
            minWidth: 150
          },
          {
            prop: 'suitMinarea',
            label: '专区适用面积区间',
            minWidth: 150,
            render: function(createElement, rows) {
              return (<div>
                {(rows.suitMinarea || '-') + '~' + (rows.suitMaxarea || '-') + '㎡'}
              </div>
              )
            }
          }, {
            prop: '',
            label: '专区款式数量',
            minWidth: 130,
            render: function(createElement, rows) {
              return (<div>
                {(rows.styleMinnum || '-') + '~' + (rows.styleMaxnum || '-') + '套'}
              </div>
              )
            }
          }, {
            prop: '',
            label: '档案面积适用区间',
            minWidth: 140,
            render: function(createElement, rows) {
              return (<div>
                {(rows.archivesMinarea || '-') + '~' + (rows.archivesMaxarea || '-') + '㎡'}
              </div>
              )
            }
          }, {
            prop: 'divide',
            label: '专区划分',
            minWidth: 130,
            render: (creat, row) => {
              if (!row.divide || !this.divideOptions) {
                return
              }
              let list = []
              if (typeof (row.divide) === 'string') {
                list = row.divide.split(',')
              } else {
                list = row.divide
              }
              const arr = []
              this.divideOptions.forEach((item) => {
                const flag = list.some(v => v === item.dictCode)
                if (flag) {
                  arr.push(item.dictName)
                }
              })
              return (<span>{ arr.toString() }</span>)
            }
          }
        ],
        btnList: this.isProduction ? null : [{
          buttonName: '新增',
          optCode: 'add',
          outerFlag: true
        },
        {
          buttonName: '编辑',
          optCode: 'edit',
          outerFlag: true
        },
        {
          buttonName: '删除',
          optCode: 'del',
          outerFlag: true
        },
        {
          buttonName: '导入',
          optCode: 'import',
          outerFlag: true
        },
        {
          buttonName: '导出',
          optCode: 'export',
          outerFlag: true
        }]
      }
    }
  },
  computed: {
    exportConfig() {
      return [{
        code: 'export',
        name: '产品上样推荐配置',
        dataApi: '/slm-admin/api/v1/configSampleRecommend/export?type=0',
        selectedRows: this.selectedRows,
        paramsRaw: {},
        filtersRaw: this.otherFilters,
        queryField: 'mainId'
      },
      {
        code: 'exportTemplate',
        name: '产品上样推荐配置模板',
        async: false,
        templateMethod: 'post',
        templateApi: '/slm-admin/api/v1/configSampleRecommend/export?type=1'
      }]
    },
    fileImportConfig() {
      return [{
        code: 'import',
        name: '新增产品上样推荐配置',
        async: false,
        apiUrl: '/slm-admin/api/v1/configSampleRecommend/importExcel?type=1'
      },
      {
        code: 'importUpdate',
        name: '修改产品上样推荐配置',
        async: false,
        apiUrl: '/slm-admin/api/v1/configSampleRecommend/importExcel?type=0'
      }]
    }
  },
  async created() {
    await this.getDictByPatchTypeAll(['ZONE_DIVISION']).then(res => {
      this.divideOptions = res.ZONE_DIVISION
    })
  },
  methods: {
    // 获取数据字典
    async getDictByPatchTypeAll(data) {
      const obj = await getDictByPatchType(data)
        .then(res => {
          return res
        })
      return obj
    },
    // 获取品类
    async getCategoryData(arr) {
      const codes = '[' + arr.join(',') + ']'
      const filterRow = [{ 'id': 'code', 'property': 'code', 'operator': 'in', 'value': codes }]
      const dataForm = new FormData()
      dataForm.append('pageFlag', false)
      dataForm.append('filtersRaw', JSON.stringify(filterRow))
      return await queryCategoryData(dataForm).then(res => {
        if (res.success) {
          return res.data.records
        }
      })
    },
    // 搜索
    async handleSearch(data) {
      if (data && data.filtersRaw) {
        const proPosition = data.filtersRaw.filter(item => item.property === 'proPosition')
        const modelCode = data.filtersRaw.filter(item => item.property === 'modelCode')
        const categoryCode = data.filtersRaw.filter(item => item.property === 'categoryCode')
        const seriesCode = data.filtersRaw.filter(item => item.property === 'seriesCode')
        let parentCode = ''
        if (categoryCode.length) {
          const plCode = [categoryCode[0].value]
          const pl = await this.getCategoryData(plCode)
          if (pl[0].parentCode) {
            parentCode = pl[0].parentCode
          } else {
            parentCode = pl[0].code
          }
        }
        if (proPosition.length > 0) {
          this.otherRaw.proPosition = proPosition[0].value
        }
        if (modelCode.length > 0) {
          this.otherRaw.modelCode = modelCode[0].value
        }
        if (categoryCode.length > 0) {
          this.otherRaw.categoryCode = parentCode
        }
        if (seriesCode.length > 0) {
          this.otherRaw.seriesCode = seriesCode[0].value
        }
        const arr = data.filtersRaw.filter(item => item.property === 'recommendProgram' || item.property === 'configStyleId' || item.property === 'configSpaceId')
        this.otherFilters = [...arr]
        this.$nextTick(() => {
          this.$refs.ProSampleRecommend.initTableData()
        })
      }
    },
    // 清空
    clearSearch() {
      this.otherRaw = {}
    },
    // 按钮组
    btnOperate(code) {
      switch (code) {
        case 'add':
          this.handleAdd()
          break
        case 'edit':
          if (!this.singleJudge(this.tableSelected, '编辑', true)) {
            return
          }
          this.handleEdit(this.tableSelected[0])
          break
        case 'submit':
          this.handleSubmit(this.tableSelected)
          break
        case 'del': // 删除

          this.edeltail(this.tableSelected)
          break
        case 'export':// 导出
          this.exportVisible = true
          break
        case 'import':// 导入
          this.importVisible = true
          break
      }
    },
    // // 导出成功
    // handleExportSuccess() {
    //   this.$message.success('导出成功！')
    // },
    // 导入成功
    handleImportSuccess() {
      this.$nextTick(() => {
        this.$refs.ProSampleRecommend.initTableData()
      })
    },
    handleAdd() {
      this.showAddPage = true
    },
    // 新增/编辑
    handleEdit(data) {
      this.activatedData = {}
      if (data) {
        this.activatedData.id = data.id
        this.activatedData.flag = 'edit'
      }
      this.showEditPage = true
    },
    // 详情
    handleDetail(data) {
      this.activatedData.id = data.id
      this.activatedData.flag = 'detail'
      this.showEditPage = true
    },
    // 选中行
    selectionChangeHandle(rows) {
      this.tableSelected = rows
      const arr = rows
      arr.forEach(item => {
        item.mainId = item.id
      })
      this.selectedRows = arr
    },
    // 删除
    edeltail() {
      if (this.tableSelected.length < 1) {
        this.$message.warning(`请选择【删除】项`)
        return false
      }
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableSelected.forEach(item => { item.dr = 1 })
        delProRecommend(this.tableSelected).then(res => {
          if (res.success === 1) {
            this.$message.success(`删除成功`)
            this.refreshTable()
          }
        })
      })
    },
    refreshTable(isInit) {
      this.$refs.ProSampleRecommend.initTableData(isInit ? '' : 'onPage')
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
